package beavers.studio.utilities;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

import beavers.studio.utilities.callbacks.WebDataCallback;

import net.rim.device.api.servicebook.ServiceBook;
import net.rim.device.api.servicebook.ServiceRecord;
import net.rim.device.api.system.CoverageInfo;
import net.rim.device.api.system.WLANInfo;
import net.rim.device.api.ui.UiApplication;

public class Utils { 
	//Get WAP2 service record
	private static ServiceRecord getWAP2ServiceRecord() { 
        ServiceBook sb = ServiceBook.getSB(); 
        ServiceRecord[] records = sb.getRecords(); 
 
        for(int i = 0; i < records.length; i++) { 
            String cid = records[i].getCid().toLowerCase(); 
            String uid = records[i].getUid().toLowerCase(); 
            if (cid.indexOf("wptcp") != -1 &&  
                    uid.indexOf("wifi") == -1 &&  
                    uid.indexOf("mms") == -1) { 
                return records[i]; 
            } 
        } 
        return null; 
    } 
	
	//Get connection parameter
	private static String getConnectionParameter() {
		//Initiate parameter
		String connectionParameters = ""; 
		
		//Get parameter according phone state
		if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) { 
		    // Connected to a WiFi access point 
		    connectionParameters = ";interface=wifi"; 
		    System.out.println("Connected using WLAN.");
		} else { 
		   int coverageStatus = CoverageInfo.getCoverageStatus(); 
		   ServiceRecord record = getWAP2ServiceRecord(); 
		   if (record != null && (coverageStatus&CoverageInfo.COVERAGE_DIRECT)==CoverageInfo.COVERAGE_DIRECT) { 
		      // Have network coverage and a WAP 2.0 service book record 
		      connectionParameters = ";deviceside=true;ConnectionUID=" + record.getUid(); 
		      System.out.println("Connected using WAP2.");
			} else if ((coverageStatus&CoverageInfo.COVERAGE_MDS)==CoverageInfo.COVERAGE_MDS) { 
			   // Have an MDS service book and network coverage 
			   connectionParameters = ";deviceside=false"; 
			   System.out.println("Connected using MDS.");
			} else if ((coverageStatus&CoverageInfo.COVERAGE_DIRECT)==CoverageInfo.COVERAGE_DIRECT) { 
			   // Have network coverage but no WAP 2.0 service book record 
			   connectionParameters = ";deviceside=true"; 
			   System.out.println("Connected using Direct TPC/IP.");
			}
		}
		
		//Return data
		return connectionParameters;
	}

	//Get bitmap from web and put it into callback
	public static void getWebData(final String m_Url, final WebDataCallback m_Callback) {
		//Create thread
		Thread m_Thread = new Thread(new Runnable() {
			public void run() {
				System.out.println("Download thread running.");
				
				//Create HTTP Connection
				HttpConnection	conn = null;
				InputStream 	is = null;
				
				try {
					//Create connection parameter (but now is not the time to use it)
					String m_Parameter = getConnectionParameter();
					System.out.println("Connection parameter is " + m_Parameter);  
					
					//Create HTTP Connection
					conn = (HttpConnection) Connector.open(m_Url, Connector.READ_WRITE, true);  
					System.out.println("HTTP Connection Created.");
					
					//Go process if response is OK
					System.out.println("Getting response code.");
					int m_Response = conn.getResponseCode();
					
					if (m_Response==HttpConnection.HTTP_OK) {
						System.out.println("HTTP response is OK");
						
						//Open input stream
						is = conn.openInputStream();
						
						//Create buffer
						byte[] m_Data = new byte[1024];// 1KB buffer
						ByteArrayOutputStream m_Stream = new ByteArrayOutputStream();
						
						System.out.println("Downloading...");
						
						//Get data
						int len = 0;
						int image_size = 0;
						while ((len=is.read(m_Data))!=-1) {
							m_Stream.write(m_Data);
							image_size += len;
						}
						
						//Move data to byte array
						m_Stream.flush();
						final byte[] m_ImageData = m_Stream.toByteArray();
						m_Stream.close();

						System.out.println("Data downloaded.");
						
						//Create Bitmap and put into callback
						UiApplication.getUiApplication().invokeLater(new Runnable() {  
		                    public void run() {  
		                    	m_Callback.callback(m_ImageData);
		                    }  
		                });						
					} else {
						System.out.println("HTTP response is " + m_Response);
						
						//Return null
						UiApplication.getUiApplication().invokeLater(new Runnable() {  
		                    public void run() {  
		                    	m_Callback.callback(null);
		                    }  
		                });	
					}
					
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					//Close stuffs
					try {
						System.out.println("Closing connection.");
						if (is!=null) is.close();
						if (conn!=null) conn.close();
					} catch (Exception e) {e.printStackTrace();}
				}
				
			}
		});
		m_Thread.start();
	}
}
